export default class CueController {
  constructor(cueBall, onShoot) {
    this.cueBall = cueBall;
    this.onShoot = onShoot;

    this.enabledThisTurn = false;
    this.dragging = false;
    this.dragStart = { x: 0, y: 0 };
    this.currentAimDir = { x: 1, y: 0 };

    this.maxPower = 1200;   // px/s
    this.powerScale = 1.5;  // 拖拽像素到力度的缩放

    // 新增：力度预览 & 回弹动画状态
    this.powerPreview = 0;
    this.recoilActive = false;
    this.recoilProgress = 0;     // 0 -> 1
    this.recoilDuration = 0.2;   // 秒
    this.recoilDir = { x: 0, y: 0 };
    this.recoilPower = 0;

    this.initEvents();
  }

  enableForTurn(enabled) {
    this.enabledThisTurn = enabled;
    this.clearAimLine();
  }

  clearAimLine() {
    // 仅保留计算数据，实际绘制在 render 中
    this.dragging = false;
  }

  initEvents() {
    wx.onTouchStart((e) => {
      if (!this.enabledThisTurn) return;
      const { clientX: x, clientY: y } = e.touches[0];
      this.dragging = true;
      this.dragStart = { x, y };
    });

    wx.onTouchMove((e) => {
      if (!this.enabledThisTurn || !this.dragging) return;
      const { clientX: x, clientY: y } = e.touches[0];

      const dx = x - this.cueBall.x;
      const dy = y - this.cueBall.y;
      const len = Math.sqrt(dx * dx + dy * dy) || 1;
      this.currentAimDir = { x: dx / len, y: dy / len };

      // 预览力度（用于显示力度条）
      const dxp = this.dragStart.x - x;
      const dyp = this.dragStart.y - y;
      const dragDistance = Math.sqrt(dxp * dxp + dyp * dyp);
      this.powerPreview = Math.min(dragDistance * (1 / this.powerScale), this.maxPower);
    });

    wx.onTouchEnd((e) => {
      if (!this.enabledThisTurn || !this.dragging) return;
      this.dragging = false;

      const { clientX: rx, clientY: ry } = e.changedTouches[0];
      const dx = this.dragStart.x - rx;
      const dy = this.dragStart.y - ry;
      const dragDistance = Math.sqrt(dx * dx + dy * dy);
      const power = Math.min(dragDistance * (1 / this.powerScale), this.maxPower);

      // 修改：先播放回弹动画，动画结束后再真正出杆
      this.startRecoil(this.currentAimDir, power);
      this.clearAimLine();
    });

    wx.onTouchCancel(() => {
      this.dragging = false;
    });
  }

  // 新增：回弹动画驱动
  update(dt) {
    if (!this.recoilActive) return;
    this.recoilProgress += Math.min(1, dt / this.recoilDuration);
    if (this.recoilProgress >= 1) {
      this.recoilActive = false;
      // 动画完成后进行实际出杆
      if (this.onShoot) {
        this.onShoot(this.recoilDir, this.recoilPower);
      }
    }
  }

  startRecoil(dir, power) {
    this.recoilActive = true;
    this.recoilProgress = 0;
    this.recoilDir = { x: dir.x, y: dir.y };
    this.recoilPower = power;
  }

  render(ctx) {
    if (!this.enabledThisTurn || !this.dragging) return;

    ctx.save();
    ctx.strokeStyle = '#ffe26b';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(this.cueBall.x, this.cueBall.y);
    ctx.lineTo(this.cueBall.x + this.currentAimDir.x * 80, this.cueBall.y + this.currentAimDir.y * 80);
    ctx.stroke();
    ctx.restore();

    // 新增：回弹动画展示（将“球杆”沿瞄准方向先后拉回/推前的视觉线段）
    if (this.recoilActive) {
      const back = 50; // 回拉最大长度
      // 前半段回拉，后半段推前，使用简单对称插值
      const t = this.recoilProgress;
      const backLen = t < 0.5 ? back * (t / 0.5) : back * (1 - (t - 0.5) / 0.5);

      const sx = this.cueBall.x - this.recoilDir.x * backLen;
      const sy = this.cueBall.y - this.recoilDir.y * backLen;
      const ex = this.cueBall.x + this.recoilDir.x * 80;
      const ey = this.cueBall.y + this.recoilDir.y * 80;

      ctx.save();
      ctx.strokeStyle = '#ffcf33';
      ctx.lineWidth = 3;
      ctx.beginPath();
      ctx.moveTo(sx, sy);
      ctx.lineTo(ex, ey);
      ctx.stroke();
      ctx.restore();
    }

    // 新增：力度条（屏幕底部）
    if (this.enabledThisTurn) {
      const barW = 180;
      const barH = 10;
      const x = this.cueBall.x - barW / 2;
      const y = this.cueBall.y + 40;

      const ratio = Math.max(0, Math.min(1, this.powerPreview / this.maxPower));

      ctx.save();
      ctx.fillStyle = 'rgba(255,255,255,0.2)';
      ctx.fillRect(x, y, barW, barH);

      const grad = ctx.createLinearGradient(x, y, x + barW, y);
      grad.addColorStop(0, '#5cf');
      grad.addColorStop(1, '#f55');
      ctx.fillStyle = grad;
      ctx.fillRect(x, y, barW * ratio, barH);

      ctx.strokeStyle = '#333';
      ctx.lineWidth = 1;
      ctx.strokeRect(x, y, barW, barH);
      ctx.restore();
    }
  }
}